//Darius Smith
//DA5 part 1

#define F_CPU 8000000UL //XTAL = 8MHZ

#include <avr/io.h>
#include <stdio.h>
#include <avr/interrupt.h>
#include <util/delay.h>

void printStringToScreen(char *sentence)//function to print output to screen
	{
	while ((*sentence !='\0'))
		{ 
		while(!(UCSR0A&(1<<UDRE0)));
			UDR0 = *sentence;
		sentence++;
		}
	}

int main(void)
{
	int val_ocr;
	double val_adc;
	char out_sentence[999]; //holds the output to print on screen
	
	DDRB = 0xFF; //sets the B port to direct to output	
	DDRD = 0xFF; //sets the D port to direct to output	
	TCCR1A = 0x00; //TCNT1 is clock driven
	TCCR1B = 0x0D; //sets WGM12 high creating CTC mode and at the same time sets the prescaler to 1024	
	ADCSRA = 0x82;	
	UCSR0B = 0x08;  //TXEN0 set high, allows serial transmition
	UCSR0C = 0x06;  //UCSZ01 and UCSZ00 set high
	UBRR0 = 0x0033;
	
	while(1)
		{
		ADCSRA |= (1<<ADSC);
		while((ADCSRA&(1<<ADIF))==0)
			{
			
			}
		if(ADC < 70)
			{
			val_adc = 70;
			} 
		else if(ADC > 530)
			{
			val_adc = 530;
			}
		else
			{
			val_adc = ((ADC - 70) * 3.8) + 250;
			}
		
		snprintf(out_sentence,sizeof(out_sentence), "%3d\r\n\n", ADC);
		printStringToScreen(out_sentence);
		
		OCR1A = 1000;
		
		while((TIFR1 & (1<<OCF1A)) == 0)
			{
			}
		
		TIFR1 |= (1 << OCF1A);
		PORTB ^= 1;
		
		if(ADC < 70)
			{
			val_adc = 250;
			} 
		else if(ADC > 500)
			{
			val_adc = ((500 - 70) * 3.8) + 250;
			}
		else
			{
			val_adc = ((ADC - 70) * 3.8) + 250;
			}
		
		val_ocr = val_adc;
		snprintf(out_sentence, sizeof(out_sentence), "%3d\r\n\n", ADC);		
		printStringToScreen(out_sentence);
		
		OCR1A = val_ocr;
		
		while((TIFR1 & (1<<OCF1A)) == 0)
			{
			}
		
		TIFR1 |= (1 << OCF1A);
		PORTB ^= 1;
		}
}